function send(res, code, message) {
	res.status(200).json({
		code,
		message
	})
}

var allQuestions = []
if(fs.existsSync('question/questions.json')) {
	var data = fs.readFileSync('question/questions.json')
	allQuestions = JSON.parse(data)
}

function signIn(req, res, next) {
	var name = req.cookies.username
	if(name) {
		next()
	} else {
		// 通过req.xhr来进行判断请求是否是由ajax发起的
		if(req.xhr) {
			send(res, 'fail', '对不起,请先登录...')
		} else {
			// 重定向
			res.direct('/')
		}
	}
}

function existQuestion(req, res, next) {
	fs.exists('question', ex => {
		if(ex) {
			next()
		} else {
			fs.mkdir('question', err => {
				if(err) {
					send(res, 'fail', '系统出错,请稍后再试...')
				} else {
					next()
				}
			})
		}
	})
}

//保存文件
function saveFile(res, fileName, data, code, message) {
	fs.writeFile(fileName, data, err => {
		if(err) {
			send(res, 'fail', '系统错误,请稍后重试...')
		} else {
			send(res, code, message)
		}
	})
}

module.exports = {
	send,
	allQuestions,
	signIn,
	saveFile,
	existQuestion
}